import {
	ref,
} from 'vue';
import CryptoJS from 'crypto-js';

// API配置
const APP_KEY = ref("");
const APP_SECRET = ref("");
const ACCESS_TOKEN = ref("");
const BASE_URL = "https://gw.superboss.cc/router";

/**
 * 生成签名
 * @param {Object} params - 参数字典
 * @param {string} signMethod - 签名方法，支持 'md5', 'hmac', 'hmac-sha256'.
 * @returns {string} 签名字符串
 */
export const generateSignature = (params, signMethod = "hmac") => {
	// 移除sign参数、byte[]类型的参数以及值为null的参数
	const filteredParams = {};
	for (const [key, value] of Object.entries(params)) {
		if (value !== null && key !== 'sign') {
			filteredParams[key] = value;
		}
	}
	// 根据参数名称的ASCII码表的顺序排序
	const sortedParams = Object.entries(filteredParams)
		.sort((a, b) => a[0].localeCompare(b[0]));

	// 将排序好的参数名和参数值拼装在一起
	const strParams = sortedParams.map(([k, v]) => `${k}${v}`).join('');
	// console.log('sign_str:' + strParams);

	const secretBytes = CryptoJS.enc.Utf8.parse(APP_SECRET.value);
	const messageBytes = CryptoJS.enc.Utf8.parse(strParams);

	if (signMethod === 'md5') {
		const hash = CryptoJS.MD5(CryptoJS.enc.Utf8.parse(APP_SECRET.value + strParams + APP_SECRET.value));
		return hash.toString();
	} else if (signMethod === 'hmac') {
		const hash = CryptoJS.HmacMD5(messageBytes, secretBytes);
		return hash.toString();
	} else if (signMethod === 'hmac-sha256') {
		const hash = CryptoJS.HmacSHA256(messageBytes, secretBytes);
		return hash.toString();
	} else {
		throw new Error("Unsupported sign method: " + signMethod);
	}
};

/**
 * 调用api
 * @param {string} method - api方法名
 * @param {Object} apiParams - api业务参数
 * @param {string} signMethod - 签名方法
 * @returns {Promise<Object>} api返回值
 */
export const callApi = async (method, apiParams = {}, signMethod = "hmac") => {
	const commonParams = {
		method: method,
		appKey: APP_KEY.value,
		timestamp: new Date(Date.now() + 288e5).toISOString().replace('T', ' ').replace(/\..+/, ''),
		format: "json",
		version: "1.0",
		sign_method: signMethod,
		session: ACCESS_TOKEN.value
	}
	// 合并参数
	const allParams = {
		...commonParams,
		...apiParams
	};
	// 生成签名
	const sign = generateSignature(allParams, signMethod);
	allParams.sign = sign;
	const headers = {
		"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
	};

	try {
		const response = await uni.request({
			url: BASE_URL,
			method: 'POST',
			header: headers,
			data: allParams,
		});
		if (response.statusCode === 200) {
			return response.data;
		} else {
			console.error('API call failed with status:', response.statusCode, response.data);
			return {
				success: false,
				message: `API call failed: Status ${response.statusCode}`
			};
		}
	} catch (error) {
		console.error('API call error:', error);
		return {
			success: false,
			message: `Network error: ${error.message}`
		};
	}
};

export const queryGoodsclassifications = () => {
	return callApi("erp.item.seller.cat.list.get");
};

export const queryWarehouse = (outerId, pageNo = 1, pageSize = 20) => {
	const params = {
		outerId,
		pageNo,
		pageSize
	};
	return callApi("erp.item.warehouse.list.get", params);
};
export const queryGoodsSpec = (mainOuterId) => {
	const params = {
		mainOuterId
	};
	return callApi("stock.api.status.query", params);
};

export const addGoodsSpecification = (itemRequestType, outerId, title, sellerCids, skus = null) => {
	const params = {};

	params.itemRequestType = itemRequestType
	params.outerId = outerId;
	params.title = title;
	params.sellerCids = sellerCids
	if (skus !== null) {
		params.skus = JSON.stringify(skus);
	}

	return callApi("erp.item.general.addorupdate", params);
};
export const editInventory = (warehouseId, stockNum, skuOuterId) => {
	const params = {};

	params.warehouseId = warehouseId;
	params.stockNum = stockNum;
	params.skuOuterIds = skuOuterId;

	return callApi("erp.item.available.stock.update", params);
};